<template>
  <MainLayout>
    <router-view></router-view>
    <div class="menu-management">
    <h2>菜单管理</h2>

    <!-- 搜索 -->
    <el-form :inline="true" class="add-menu-form">
      <el-form-item v-if="!isNoShowAdvancedSearch">
        <el-input v-model="newMenu.name" placeholder="请输入菜单名称/路由路径" />
      </el-form-item>
      <el-form-item>
        <template v-if="isNoShowAdvancedSearch">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="菜单名称" :label-width="70">
                <el-input v-model="newMenu.name" placeholder="请输入菜单名称" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="路由路径" :label-width="70">
                <el-input v-model="newMenu.url" placeholder="请输入路由路径" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="类型" :label-width="70">
                <el-select v-model="newMenu.type" placeholder="请选择类型" style="width: 100px;">
                  <el-option label="目录" :value="0" />
                  <el-option label="菜单" :value="1" />
                  <el-option label="按钮" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="图标" :label-width="70">
                <el-input v-model="newMenu.icon" placeholder="请输入图标" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="排序" :label-width="70">
                <el-input v-model="newMenu.sort" placeholder="请输入排序" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="权限标识" :label-width="70">
                <el-input v-model="newMenu.perms" placeholder="请输入权限标识(如sys:user:list)" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="组件标识" :label-width="70">
                <el-input v-model="newMenu.componentName" placeholder="请输入组件标识" />
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button type="text" style="width: 80px;" @click="toggleAdvancedSearch">
          {{ isNoShowAdvancedSearch ? '收起' : '高级搜索' }}
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 添加菜单/批量删除 -->
    <el-form :inline="true" style="float: right;">
      <el-form-item>
        <el-button type="primary" @click="openDialog('create')">添加菜单</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
      </el-form-item>
    </el-form>

    <!-- 菜单列表 -->
    <el-table
      :data="menus"
      style="width: 100%; max-height: 400px; height: 400px; overflow-y: auto;"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="菜单名称">
        <template #default="scope">
          <div class="ellipsis">{{ scope.row.name }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="url" label="菜单路由">
        <template #default="scope">
          <div class="ellipsis">{{ scope.row.url }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="菜单类型">
        <template #default="scope">
          <div class="ellipsis">{{ scope.row.type === 0 ? '目录' : (scope.row.type === 1 ? '菜单' : '按钮') }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="icon" label="菜单图标">
        <template #default="scope">
          <div class="ellipsis">{{ scope.row.icon }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="菜单排序">
        <template #default="scope">
          <div class="ellipsis">{{ scope.row.sort }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="perms" label="菜单权限标识">
        <template #default="scope">
          <div class="ellipsis">{{ scope.row.perms }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="componentName" label="菜单组件标识">
        <template #default="scope">
          <div class="ellipsis">{{ scope.row.componentName }}</div>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openDialog('edit', scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteMenu(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="pagination"
      background
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handlePageChange"
    />



    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="40%">
  <el-form :model="currentMenu" label-width="100px" label-position="left">
    <!-- 手动写入表单项 -->
    <el-form-item label="父级菜单">
      <el-select v-model="currentMenu.parentId" style="width: 100px;">
        <el-option label="无父级" :value="0" />
        <el-option v-for="menu in menus" :key="menu.id" :label="menu.name" :value="menu.id" />
      </el-select>
    </el-form-item>
    <el-form-item label="菜单名称">
      <el-input v-model="currentMenu.name" />
    </el-form-item>
    <el-form-item label="路由路径">
      <el-input v-model="currentMenu.url" />
    </el-form-item>
    <el-form-item label="类型">
      <el-select v-model="currentMenu.type" style="width: 100px;">
        <el-option label="目录" :value="0" />
        <el-option label="菜单" :value="1" />
        <el-option label="按钮" :value="2" />
      </el-select>
    </el-form-item>
    <el-form-item label="图标">
      <el-input v-model="currentMenu.icon" />
    </el-form-item>
    <el-form-item label="排序">
      <el-input v-model="currentMenu.sort" />
    </el-form-item>
    <el-form-item label="权限标识">
      <el-input v-model="currentMenu.perms" />
    </el-form-item>
    <el-form-item label="组件标识">
      <el-input v-model="currentMenu.componentName" />
    </el-form-item>
  </el-form>
  <template #footer>
    <el-button @click="dialogVisible = false">取消</el-button>
    <el-button type="primary" @click="CUMenu">保存</el-button>
  </template>
</el-dialog>

  </div>
  </MainLayout>
</template>

<script>
import MainLayout from '@/layouts/MainLayout.vue'
export default {
  components: { MainLayout },
  data() {
    return {
      isNoShowAdvancedSearch: false,
      menus: [],
      // 搜索属性
      newMenu: {
        name: '',
        url: '',
        type: '',
        icon: '',
        sort: '',
        perms: '',
        componentName: ''
      },
      // 详情属性
      isViewingDetail: false,
      menuDetail: {},
      // 编辑属性 对话式
      dialogMode: '',
      currentMenu: this.defaultMenu(),
      dialogVisible: false,
      dialogTitle: '',

      // 分页属性
      currentPage: 1,
      pageSize: 10,

      isEditing: false,
      editingMenu: {
        id: null,
        name: '',
        path: '',
        icon: '',
        componentName: ''
      },
      selectedMenus: []
    };
  },
  computed: {},
  methods: {
    defaultMenu() {
      return {
        parentId: "0",
        id: null,
        name: '',
        url: '',
        type: '',
        icon: '',
        sort: '',
        perms: '',
        componentName: ''
      };
    },

    // 高级搜索按钮逻辑
    toggleAdvancedSearch() {
      this.isNoShowAdvancedSearch = !this.isNoShowAdvancedSearch;
      if (!this.isNoShowAdvancedSearch) {
        this.newMenu.name = '';
        this.newMenu.url = '';
        this.newMenu.type = '';
        this.newMenu.icon = '';
        this.newMenu.sort = '';
        this.newMenu.perms = '';
        this.newMenu.componentName= '';
      }
    },

    // 打开编辑或添加对话框
    openDialog(mode, menu = {}) {
      this.dialogMode = mode;
      this.dialogTitle = mode === 'create' ? '添加菜单' : '编辑菜单';
      this.currentMenu = mode === 'edit' ? { ...menu } : this.defaultMenu();
      this.dialogVisible = true;
    },

    // 删除菜单
    async deleteMenu(id) {
      try {
        const response = await fetch(`http://localhost:8090/menu/DById/${id}`, { method: 'GET' });
        const data = await response.json();

        if (data.code == 200) {
          this.menus = this.menus.filter(r => r.id !== id);
          this.$message.success('删除成功');
        } else {
          this.$message.error('删除失败');
        }
      } catch (err) {
        console.error('删除失败:', err);
        this.$message.error('出错啦');
      }
    },

    // 分页方法
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchMenus();
    },

    // 获取菜单数据
    async fetchMenus() {
      try {
        const response = await fetch('http://localhost:8090/menu/P', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            pageNo: this.currentPage,
            pageSize: this.pageSize,
            name: this.newMenu.name,
            url: this.newMenu.url,
            type: this.newMenu.type,
            icon: this.newMenu.icon,
            sort: this.newMenu.sort,
            perms: this.newMenu.perms,
            componentName: this.newMenu.componentName
          })
        });

        const data = await response.json();
        console.log('菜单API 响应数据:', data); // 添加调试日志
        if (data.code == 200) {
          this.menus = data.data.records;
          this.total = data.data.total;
        } else {
          this.$message.error(`获取菜单数据失败: ${data.message}`);
        }
      } catch (err) {
        console.error('获取菜单数据失败:', err);
        this.$message.error('获取菜单数据失败，请检查网络连接');
      }
    },

    // 创建/更新菜单
    async CUMenu() {
      const url = this.dialogMode === 'create' ? 'http://localhost:8090/menu/C' : 'http://localhost:8090/menu/UById';

      try {
        const requestData = this.dialogMode === 'create'
          ? { ...this.currentMenu, id: undefined }
          : this.currentMenu;

        const response = await fetch(url, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(requestData)
        });

        const data = await response.json();
        if (data.code == 200) {
          this.dialogVisible = false;
          this.$message.success(`${this.dialogTitle}成功`);
          this.fetchMenus(); // 刷新菜单列表
        } else {
          this.$message.error(`${this.dialogTitle}失败`);
        }
      } catch (err) {
        console.error(`${this.dialogTitle}失败:`, err);
        this.$message.error('发生错误');
      }
    },

    // 搜索按钮
    onSearch() {
      this.currentPage = 1;
      this.fetchMenus();
    },

    // 批量删除
    batchDelete() {
      const ids = this.selectedMenus.map(r => r.id);
      this.$confirm('确定要删除选中的菜单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await fetch('http://localhost:8090/menu/DByIds', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(ids)
          });
          const data = await response.json();
          if (data.code == 200) {
            this.menus = this.menus.filter(r => !ids.includes(r.id));
            this.selectedMenus = [];
            this.$message.success('批量删除成功');
          } else {
            this.$message.error('批量删除失败');
          }
        } catch (err) {
          console.error('批量删除失败:', err);
          this.$message.error('出错啦');
        }
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' });
      });
    },

    // 保存编辑
    saveEdit() {
      const index = this.menus.findIndex(m => m.id === this.editingMenu.id);
      if (index !== -1) {
        this.menus.splice(index, 1, this.editingMenu);
      }
      this.cancelEdit();
    },
    cancelEdit() {
      this.isEditing = false;
      this.editingMenu = { id: null, name: '', path: '', icon: '', componentName: ''};
    },

    // 表格选择变化
    handleSelectionChange(selection) {
      this.selectedMenus = selection;
    },

    // 点击行查看详情
    handleRowClick(row) {
      this.menuDetail = row;
      this.isViewingDetail = true;
    }
  },
  beforeUnmount() {
    this.isEditing = false;
    this.editingMenu = { id: null, name: '', path: '', icon: '', componentName: '' };
    this.selectedMenus = [];
  },
  mounted() {
    this.fetchMenus();
  }
};
</script>

<style scoped>
.menu-management {
  width: 100%;
  min-height: 100vh;
  margin: 0;
  padding: 10px;
  background-color: #fff;
  padding-bottom: 100px;
}

/* 禁止页面滚动 */
body {
  overflow: hidden;
}

.pagination {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: 30px;
  margin-top: 24px;
  justify-content: center;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.el-dialog {
  border-radius: 8px;
}

.el-dialog__header {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  border-radius: 8px 8px 0 0;
  padding: 16px;
}

.el-dialog__body {
  padding: 20px;
}

.el-dialog__footer {
  padding: 16px;
  border-top: 1px solid #ebeef5;
  background-color: #f5f7fa;
  box-shadow: none;
}

.menu-management h2 {
  margin-top: 10px;
  margin-bottom: 24px;
  font-size: 24px;
  font-weight: 500;
  text-align: left;
}
</style>
